from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.db import connection
from django.utils.dateparse import parse_date
from django.urls import reverse
from datetime import datetime
from django.shortcuts import render
from django.http import JsonResponse
import json
from urllib.parse import unquote
from django.http import QueryDict
from decimal import Decimal, ROUND_HALF_UP
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage

# 定义列名列表
COLUMN_NAMES = [
    '检验单号', '检验日期', '存货编码', '存货名称', '规格型号',
    '品牌', '供应商编码', '供应商名称', '批号', '生产日期', '合格数量', '不良数量'
]

def index(request):
    with connection.cursor() as cursor:
        cursor.execute('SELECT * FROM CHECK_VIEW')
        datas = cursor.fetchall()

    # 将元组列表转换为字典列表
    datas = [dict(zip(COLUMN_NAMES, data)) for data in datas]
    print(len(datas))

    # 实例化分页器
    paginator = Paginator(datas, 80)  # 每页80条数据

     # 获取请求中的页码参数，如果没有提供或不是有效页码，则默认为第一页
    page = request.GET.get('page')
    if page is not None:
        try:
            datas = paginator.page(page)
        except PageNotAnInteger:
            # 如果请求的页码不是整数，则返回第一页
            datas = paginator.page(1)
        except EmptyPage:
            # 如果请求的页码超出范围，则返回最后一页
            datas = paginator.page(paginator.num_pages)
    else:
        datas = paginator.page(1)





    # 遍历列表，将每个字典中的Decimal转换为不带小数点和后面零的字符串
    for data in datas:
        if '检验单号' in data:
            cleaned_up_number = str(data['检验单号']).lstrip('0')  # 去除前面的零
            # 如果去零后不是空字符串，确保检验单号至少有一个数字
            if cleaned_up_number:
                data['检验单号'] = cleaned_up_number
            else:
                data['检验单号'] = '0'  # 如果全是零，设为 '0'
        if '合格数量' in data and isinstance(data['合格数量'], Decimal):
            # 四舍五入并规范化Decimal值
            data['合格数量'] = data['合格数量'].quantize(Decimal('1'), rounding=ROUND_HALF_UP).normalize()
    # 检查并格式化 '不良数量'
        if '不良数量' in data and isinstance(data['不良数量'], Decimal):
            data['不良数量'] = data['不良数量'].quantize(Decimal('1'), rounding=ROUND_HALF_UP).normalize()
    # print(datas)

    template = loader.get_template('index.html')
    context = {
        'datas': datas,
        # 'distinct_batches': distinct_batches,  # 如果你决定使用这个变量，请取消注释
        # 'paginator': paginator  # 将分页器对象传递给模板
    }
    return HttpResponse(template.render(context, request))

def filter_by_date(request):
    if request.method == 'POST':
        date = request.POST.get('date')
        selected_date = date  # 保存用户选择的日期
        if date:
            parsed_date = datetime.strptime(date, '%Y-%m-%d').date()
            with connection.cursor() as cursor:
                cursor.execute('SELECT * FROM CHECK_VIEW WHERE 检验日期 = %s', [parsed_date])
                datas = cursor.fetchall()
            datas = [dict(zip(COLUMN_NAMES, data)) for data in datas]

            # 遍历列表，将每个字典中的Decimal转换为不带小数点和后面零的字符串
            for data in datas:
                if '检验单号' in data:
                    cleaned_up_number = str(data['检验单号']).lstrip('0')  # 去除前面的零
                    # 如果去零后不是空字符串，确保检验单号至少有一个数字
                    if cleaned_up_number:
                        data['检验单号'] = cleaned_up_number
                    else:
                        data['检验单号'] = '0'  # 如果全是零，设为 '0'              
                if '合格数量' in data and isinstance(data['合格数量'], Decimal):
                    # 四舍五入并规范化Decimal值
                    data['合格数量'] = data['合格数量'].quantize(Decimal('1'), rounding=ROUND_HALF_UP).normalize()
            # 检查并格式化 '不良数量'
                if '不良数量' in data and isinstance(data['不良数量'], Decimal):
                    data['不良数量'] = data['不良数量'].quantize(Decimal('1'), rounding=ROUND_HALF_UP).normalize()
            
        else:
            datas = []
    else:
        return HttpResponseRedirect(reverse('index'))

    template = loader.get_template('index.html')
    context = {
        'datas': datas,
        'selected_date': selected_date  # 添加选择的日期到上下文
    }
    return HttpResponse(template.render(context, request))


def filter_by_batch(request):
    if request.method == 'POST':
        # 使用中文 '批号' 来获取表单数据
        batch = request.POST.get('批号')
        if batch:
            # print("有batch")
            # print(batch)
             # 清理 batch 变量，去除首尾的空格和换行符
            batch = batch.strip()
            with connection.cursor() as cursor:
                # 确保 SQL 查询语句使用正确的列名
                cursor.execute('SELECT * FROM CHECK_VIEW WHERE 批号 = %s', [batch])
                results = cursor.fetchall()  # 获取所有查询结果
                # print("有result")
                # print(results)
                # 将结果转换为字典，并去除重复项
                unique_datas = {tuple(data) for data in results}
                datas = [list(data) for data in unique_datas]  # 转换为列表
            datas = [dict(zip(COLUMN_NAMES, data)) for data in datas]
            # print("查看datas")
            # print(datas)

            # 遍历列表，将每个字典中的Decimal转换为不带小数点和后面零的字符串
            for data in datas:
                if '检验单号' in data:
                    cleaned_up_number = str(data['检验单号']).lstrip('0')  # 去除前面的零
                    # 如果去零后不是空字符串，确保检验单号至少有一个数字
                    if cleaned_up_number:
                        data['检验单号'] = cleaned_up_number
                    else:
                        data['检验单号'] = '0'  # 如果全是零，设为 '0'
                if '合格数量' in data and isinstance(data['合格数量'], Decimal):
                    # 四舍五入并规范化Decimal值
                    data['合格数量'] = data['合格数量'].quantize(Decimal('1'), rounding=ROUND_HALF_UP).normalize()
                # 检查并格式化 '不良数量'
                if '不良数量' in data and isinstance(data['不良数量'], Decimal):
                    data['不良数量'] = data['不良数量'].quantize(Decimal('1'), rounding=ROUND_HALF_UP).normalize()
            # print(datas)
        else:
            datas = []
    else:
        return HttpResponseRedirect(reverse('index'))

    template = loader.get_template('index.html')
    context = {
        'datas': datas,
    }
    return HttpResponse(template.render(context, request))


def selected_data(request):
    if request.method == 'POST':
        # 从请求中获取数据
        selected_data_array = json.loads(request.body.decode('utf-8'))

        # 直接返回JSON响应
        return JsonResponse({
            'success': True,
            'data': selected_data_array,
        })
    else:
        # 如果不是POST请求，返回错误状态
        return JsonResponse({'success': False}, status=400)
              
def show_selected_data(request):
    context = {}
    if request.method == 'GET':
        # 尝试从查询参数中获取数据
        data_string = request.GET.get('data')
        if data_string:
            try:
                # 解码URL编码的字符串
                decoded_data_string = unquote(data_string)
                # 解析JSON数据
                data = json.loads(decoded_data_string)
                # 检查数据是否为列表
                if isinstance(data, list):
                    # 遍历列表中的每个字典
                    for item in data:
                        # 检查并替换每个字典中所有出现的"#"为"%"
                        for key in item:
                            if isinstance(item[key], str):
                                item[key] = item[key].replace("#", "%")
                context['data'] = data
            except json.JSONDecodeError as e:
                # 打印错误信息
                print(f"Error decoding JSON data: {e}")
                return JsonResponse({'success': False, 'error': 'Error decoding JSON data'}, status=400)

    # 渲染模板并传递上下文
    template = loader.get_template('selected_data.html')
    return render(request, 'selected_data.html', context)